package com.atguigu.teach.juc;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class MyResource
{
    public synchronized void m1()
    {
        System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
        //暂停几秒钟线程
        try { TimeUnit.SECONDS.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); }
    }

    Lock lock = new ReentrantLock();
    public void m2() throws InterruptedException
    {
        //if(lock.tryLock())
        if(lock.tryLock(2,TimeUnit.SECONDS))
        {
            try
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"---come in");
                try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); }
            }finally {
                lock.unlock();
            }
        }else{
            System.out.println(Thread.currentThread().getName()+"\t"+"---抢锁失败");
        }
    }
}

/**
 * @auther zzyy
 * @create 2021-08-05 17:58
 * synchronized vs ReentrantLock
 *
 *  1 synchronized是java的内置关键字而ReentrantLock时java5以后的新发布的类
 *  2 synchronized一旦申请，如果获取不到锁会一直阻塞，这个阻塞的过程，用户无法控制
 */
public class SyncVsReentrantLockDemo
{
    public static void main(String[] args)
    {
        MyResource myResource = new MyResource();

        new Thread(() -> {
            try {
                myResource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t1").start();

        new Thread(() -> {
            try {
                myResource.m2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"t2").start();
    }
}
